package com.steven.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * Scattering：将数据写入到写入到buffer 可以采用buffer数组依次写入 【分散】
 * Gathering：从buffer读取数据时 可以采用buffer数组 按顺序依次读取
 */
public class ScatteringAndGatheringTest {

    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);

        //绑定监听
        serverSocketChannel.socket().bind(inetSocketAddress);

        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        //等待连接
        SocketChannel socketChannel = serverSocketChannel.accept();
        while (true){
            int byteRead =0;
            while (byteRead<8) {
                long read = socketChannel.read(byteBuffers);
                byteRead +=read;
                System.out.println("byteread:"+byteRead);
                //当前buffer 的postion limit
                for (ByteBuffer v : byteBuffers){
                    System.out.println("position:"+v.position()+"limit:"+v.limit());
                }
            }
            //反转
            for (ByteBuffer v : byteBuffers){
                v.flip();
            }
            int byteWrite =0;
            while (byteWrite<8){
                long write = socketChannel.write(byteBuffers);
                byteWrite+=write;
            }
            //重置位
            for (ByteBuffer v : byteBuffers){
                v.clear();
            }
            System.out.println("byteRead:"+byteRead+",bytewirte:"+byteWrite+",mesagelength:"+8);
        }
    }
}
